// mock
const Mock = require('mockjs')
const BodyParser = require('body-parser')
/**
 * 班级名字 1910A
 * 教室名字
 * 课程名字
 * 学生数量
 */

const classlist = ['1910A', '1909A', '1908A']
const courseList = ['js上', 'js下', '项目实战', 'react']

const data = Mock.mock({
  'list|40': [
    {
      id: '@id()',
      itemClass: `@integer(1901, 2000)` + 'A', // 1910A
      className: '@integer(6300, 6399)',
      'course|+1': courseList,
      'student|20': [
        {
          id: '@id()',
          studentName: '@cname()',
        },
      ],
    },
  ],
})

module.exports = (app) => {
  app.use(BodyParser.json())

  // 1. 登陆接口 / 2. 用户信息接口
  app.post('/api/login', (req, res) => {
    const { username, password } = req.body
    res.json({
      code: 0,
      msg: 'success',
      data: { token: `${username}_${password}`, userInfo: { avatar: 'https://www.robohash.org/81', username } },
    })
  })

  // 列表接口
  app.get('/api/list', (req, res) => {
    // const { page = 1, size = 10 } = req.query
    res.json({
      code: 0,
      msg: 'success',
      // data: { total: data.list.length, list: data.list.slice((page - 1) * size, page * size) },
      data: { total: data.list.length, list: data.list },
    })
  })

  // 添加接口
  /**
   * itemClass: 添加的班级名字 1910A
   * classname: 选择的教室号码
   * course:  选择的课程
   * studentList: 添加
   */
  app.post('/api/addItem', (req, res) => {
    const { itemClass, className, course, studentList } = req.body
    data.list.push({
      id: data.list.length + 1,
      itemClass,
      className,
      course,
      studentList,
    })
    res.json({
      code: 0,
      msg: '添加成功',
      data: data.list,
    })
  })
  /***
   * 编辑接口
   */
  app.post('/api/editItem', (req, res) => {
    const { id, itemClass, className, course, studentList } = req.body
    data.list.splice(
      data.list.findIndex((v) => v.id == id),
      1,
      {
        id,
        itemClass,
        className,
        course,
        studentList,
      }
    )
    res.json({
      code: 0,
      msg: '添加成功',
      data: data.list,
    })
  })

  /**
   * @name 删除接口
   * @url /api/deleteItem
   * @params {id}
   *
   */
  app.get('/api/deleteItem', (req, res) => {
    const { id } = req.query
    data.list.splice(
      data.list.findIndex((v) => v.id == id),
      1
    )
    res.json({
      code: 0,
      msg: '添加成功',
      data: data.list,
    })
  })

  /**
   * @name 搜索接口
   * @params { 名字，教室，课程 } 精确搜索
   * @name 模糊搜索 input
   */
  app.get('/api/search', (req, res) => {})

  /**
   *
   * @name 模糊接口
   *
   */
  app.get('/api/hazySearch', (req, res) => {
    const { keyWords } = req.query
    res.json({
      code: 0,
      msg: 'success',
      data: data.list.filter((item) => {
        if (item.className.includes(keyWords) || item.itemClass.includes(keyWords) || item.course.includes(keyWords)) {
          return item
        }
      }),
    })
  })
}
